package ink.xiaobaibai.common.delay;

import ink.xiaobaibai.common.TimedTask;
import ink.xiaobaibai.entity.BuyTimedTask;
import ink.xiaobaibai.entity.MonthlyTimedTask;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @description: 定时任务的延时对象
 * @author: 小白白
 * @create: 2021-06-03
 **/

public class DeviceDelayItemByTimedTask extends DeviceDelayItem {

    /**
     * 时间链表
     */
    private LinkedList<TimeNode> linkedList;
    /**
     * 定时表id
     */
    private Integer id;

    /**
     * 是否为购买业务的
     */
    private boolean isBuyTime;

    public DeviceDelayItemByTimedTask(BuyTimedTask buyTimedTask) {
        super(buyTimedTask.getDeviceId(), buyTimedTask.getTimedTask().getTimeNodeList().get(0).getStartTime());
        this.linkedList = new LinkedList<>();
        this.getTimeNodeLinkedList(buyTimedTask);
        this.id = buyTimedTask.getId();
    }

    public DeviceDelayItemByTimedTask(MonthlyTimedTask monthlyTimedTask) {
        super(monthlyTimedTask.getDeviceId(), monthlyTimedTask.getTimedTask().getTimeNodeList().get(0).getStartTime());
        this.linkedList = new LinkedList<>();
        this.getTimeNodeLinkedList(monthlyTimedTask);
        this.id = monthlyTimedTask.getId();
    }

    private void getTimeNodeLinkedList(BuyTimedTask buyTimedTask) {
        List<TimedTask.TimeNode> timeNodeList = buyTimedTask.getTimedTask().getTimeNodeList();
        for (TimedTask.TimeNode node : timeNodeList) {
            TimeNode timeNode = new TimeNode(node.getStartTime(), node.getEndTime());
            this.linkedList.addLast(timeNode);
        }
    }

    private void getTimeNodeLinkedList(MonthlyTimedTask monthlyTimedTask) {
        List<TimedTask.TimeNode> timeNodeList = monthlyTimedTask.getTimedTask().getTimeNodeList();
        for (TimedTask.TimeNode node : timeNodeList) {
            TimeNode timeNode = new TimeNode(node.getStartTime(), node.getEndTime());
            this.linkedList.addLast(timeNode);
        }
    }

    public Integer getId() {
        return this.id;
    }

    public boolean haveNext() {
        if (this.linkedList.size() != 0) {
            //并且更新 延时接口的时间
            this.setExpiredTime(this.linkedList.getFirst().startTime);
            return true;
        }
        return false;
    }

    public Integer getOpenMin() {
        //获取开启分钟数
        int time = (int) (this.linkedList.getFirst().startTime.getTime() - this.linkedList.getFirst().endTime.getTime());
        this.linkedList.removeFirst();
        return time / 1000 / 60;
    }

    private static class TimeNode {
        public Date startTime;
        public Date endTime;

        public TimeNode(Date startTime, Date endTime) {
            this.startTime = startTime;
            this.endTime = endTime;
        }
    }

    public boolean isBuyTime() {
        return this.isBuyTime;
    }

    public void isBuyTime(boolean flag) {
        this.isBuyTime = flag;
    }

}
